import React, { useState, useEffect } from 'react';
import styles from './index.less';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Form,
  Input,
  Upload,
  DatePicker,
  message,
  Select,
  Switch,
  InputNumber,
} from 'antd';
import moment from 'moment';
import E from 'wangeditor';
import { format } from 'prettier';

const { nsBusinessAdd, nsBusinessEdit, nsTypeList } = api;

const { Option } = Select;

let editor: any = null;
export default (props: any) => {
  const [form] = Form.useForm();
  // form.setFieldsValue()

  const { manageId, schoolId } = JSON.parse(sessionStorage.info).userInfo;
  const isAdd = props.history.location.state.isAdd;
  const { initData } = props.history.location.state;
  const [content, setContent] = useState('');
  const [content2, setContent2] = useState('');
  // 商家类型列表
  const [nsType, setNsType] = useState([]);
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 4, span: 16 },
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  const [fileList1, seFileList1]: any = useState([]);
  const [fileList2, seFileList2]: any = useState([]);
  const onchange1 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList1].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList1(list);
    } else {
      seFileList1(fileLists);
    }
  };
  const onchange2 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList2].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList2(list);
    } else {
      seFileList2(fileLists);
    }
  };
  // 格式化商家类型
  const formatType = (arr: any, attr: any) => {
    const arrReturn = arr.filter((item: any) => item.id === attr);
    return arrReturn.length ? arrReturn[0] : [];
  };

  const onFinish = (v: any) => {
    if (fileList1.length && fileList2.length && editor.txt.html()) {
      let srcs = '';
      fileList1.map((item: any) => {
        srcs += `${item.url}&`;
      });
      srcs = srcs.slice(0, -1);

      let srcs2 = '';
      fileList2.map((item: any) => {
        srcs2 += `${item.url}&`;
      });
      srcs2 = srcs2.slice(0, -1);
      const { title, nsTypeId, price, numTotal, ord } = v;
      const params = {
        loginManageId: manageId,
        uSchoolId: schoolId,
        title,
        nsTypeId,
        price,
        numTotal,
        ord,
        detail: editor.txt.html(),
        src: srcs,
        url: srcs2,
      };
      if (isAdd) {
        nsBusinessAdd({ ...params }).then(_ => {
          props.history.push({
            pathname: '/nsBusiness',
          });
        });
      } else {
        nsBusinessEdit({ ...params, id: initData.id }).then(res => {
          props.history.push({
            pathname: '/nsBusiness',
          });
        });
      }
    } else {
      if (!fileList1.length) {
        message.error('请上传详情图片');
      }
      if (!fileList2.length) {
        message.error('请上传列表图片');
      }
      if (!editor.txt.html()) {
        message.error('请编写活动详情');
      }
    }
  };

  const getTypeList = () => {
    nsTypeList({
      uSchoolId: schoolId,
    }).then(res => {
      setNsType(res.data);
    });
  };
  useEffect(() => {
    getTypeList();
    // 富文本1
    editor = new E('#edit');
    editor.config.uploadImgServer = `${process.env.apiUrl}upload/edit`;
    editor.config.showFullScreen = false;
    editor.config.onchange = (newHtml: any) => {
      setContent(newHtml);
    };
    editor.create();
    if (!isAdd) {
      const arr1: any = [];
      const arr2: any = [];
      initData.src.split('&').map((item: any, i: any) => {
        arr1.push({
          uid: i,
          url: item,
        });
      });
      initData.url.split('&').map((item: any, i: any) => {
        arr2.push({
          uid: i,
          url: item,
        });
      });
      seFileList1(arr1);
      seFileList2(arr2);
      editor.txt.html(initData.detail);
    }
    return () => {
      editor.destroy();
    };
  }, []);
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <Form
          className={styles.form}
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
            initialValue={isAdd ? '' : initData.title}
          >
            <Input.TextArea />
          </Form.Item>
          <Form.Item
            label="类型"
            name="nsTypeId"
            rules={[{ required: true, message: '请选择类型' }]}
            initialValue={isAdd ? '' : initData.nsTypeId}
          >
            <Select style={{ width: 300 }} placeholder="请选择..." allowClear>
              {nsType.map((item: any, i: any) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '请输入价格' }]}
            initialValue={isAdd ? '' : initData.price}
          >
            <InputNumber min={0.01} />
          </Form.Item>
          <Form.Item
            label="券总量"
            name="numTotal"
            rules={[{ required: true, message: '请输入券总量' }]}
            initialValue={isAdd ? '' : initData.numTotal}
          >
            <InputNumber min={1} />
          </Form.Item>
          <Form.Item
            label="爆款区排序"
            name="ord"
            rules={[{ required: true, message: '爆款区排序' }]}
            initialValue={isAdd ? '' : initData.ord}
          >
            <InputNumber
              placeholder="非负数，值越大排序越靠前"
              step={1}
              style={{ width: 300 }}
              min={0}
            />
          </Form.Item>
          <Form.Item
            label="商家列表图片（单张）"
            name="url"
            rules={[{ required: false, message: '商家列表图片（单张）' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList2}
              // onPreview={this.handlePreview}
              onChange={onchange2}
            >
              {fileList2.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            label="商家详情图片（多张）"
            name="src"
            rules={[{ required: false, message: '商家详情图片（多张）' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList1}
              // onPreview={this.handlePreview}
              onChange={onchange1}
            >
              {fileList1.length >= 6 ? null : uploadButton}
            </Upload>
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : initData.detail}
            label="详情"
            name="detail"
            rules={[{ required: false, message: '请输入详情' }]}
          >
            <div id="edit"></div>
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </CardCommon>
  );
};
